const Websocket = require('ws')
const path = require('path')
const fileUtils = require('../utils/file_utils')
// 创建Websocket对象
const wss = new Websocket.Server({
  port: 9998
})

module.exports.listen = () => {
  // 监听事件
  wss.on('connection', client => {
    // 监听客户端发送到服务端的数据
    client.on('message', async messageText => {
      let jsonStr = JSON.parse(messageText.toString())
      if (jsonStr.action === 'getData') {
        let dataPath = '../data/' + jsonStr.chartName + '.json'
        dataPath = path.join(__dirname, dataPath)
        jsonStr.data = await fileUtils.getFileJsonData(dataPath)
        client.send(JSON.stringify(jsonStr))
      } else {
        // 获取所有客户端的所有连接
        wss.clients.forEach(client => {
          client.send(messageText.toString())
        })
      }
    })
  })
}
